#include <rtthread.h>
#include <drv_gpio.h>
#include "rtdbg.h"
#include <rtdevice.h>

#define BEEP_PWM    "pwm8"
#define BEEP_PWM_CHN    1

struct rt_device_pwm *beep_dev;
static rt_uint32_t period = 5000;
static rt_uint32_t pulse = 0;


static int beep_init(void)
{
    beep_dev = (struct rt_device_pwm*)rt_device_find(BEEP_PWM);
    if(beep_dev == RT_NULL)
    {
        LOG_E("beep device find errro");
        return RT_ERROR;
    }

    if(rt_pwm_set(beep_dev, BEEP_PWM_CHN, period, pulse) != RT_EOK)
    {
        LOG_E("beep device set message error");
        return RT_ERROR;
    }
    rt_pwm_enable(beep_dev, BEEP_PWM_CHN);

    return RT_EOK;
}

INIT_COMPONENT_EXPORT(beep_init);

/**
 * 设置蜂鸣器的音量
 * pulse_100 : 50~100
 */
void beep_set_period(rt_uint8_t pulse_100)
{
    if(pulse_100 < 50) pulse_100 = 50;
    if(pulse_100 > 100) pulse_100 = 100;
    rt_pwm_set(beep_dev, BEEP_PWM_CHN, period, 50*pulse_100);
}

void beep_flashing(void)
{
    rt_pwm_set(beep_dev, BEEP_PWM_CHN, period, period);
    rt_thread_mdelay(100);
    rt_pwm_set(beep_dev, BEEP_PWM_CHN, period, 0);
    rt_thread_mdelay(100);
}